package edu.dublbo.generator.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author habitplus
 * @since 2020-12-27 15:13
 */
public class JwtUtils {
    private final static Logger logger = LoggerFactory.getLogger(JwtUtils.class);
    // 过期时间，默认为 30分钟
    private long expireTime;

    // token 私钥
    private String tokenSecret;

    public JwtUtils(long expireTime, String tokenSecret) {
        this.expireTime = expireTime;
        this.tokenSecret = tokenSecret;
    }

    /**
     * 生成签名
     */
    public String sign(String userName, String userId) {
        //过期时间
        Date date = new Date(System.currentTimeMillis() + expireTime);
        //私钥加密算法
        Algorithm algorithm = Algorithm.HMAC256(tokenSecret);
        //设置头部信息
        Map<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        //附带加密的信息
        return JWT.create()
                .withHeader(header)
                .withClaim("usr", userName)
                .withClaim("uid", userId)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    /**
     * token解码，验证权限
     */
    public boolean verify(String token) {
        Algorithm algorithm = Algorithm.HMAC256(tokenSecret);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        // 判断是否过期
//        Date endDate = jwt.getExpiresAt();
        Date curDate = new Date();
        if (jwt.getExpiresAt().after(curDate)) {
            // 未过期，获取当前登录的用户
            Map<String, Claim> claims = jwt.getClaims();
            String userId = claims.get("uid").asString();
            String userName = claims.get("usr").asString();
            logger.info("Jwt Verify userId = {}, userName = {}", userId, userName);
            return true;
        } else return false;

    }

    /**
     * token提取内容
     */
//    public static Admin getAdmin(String token) {
//        try {
//            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
//            JWTVerifier verifier = JWT.require(algorithm).build();
//            DecodedJWT jwt = verifier.verify(token);
//            Admin admin = new Admin();
//            admin.setName(jwt.getClaim("loginName").toString());
//            admin.setId(Integer.parseInt(jwt.getClaim("userID").toString()));
//            return admin;
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//            return null;
//        }
//    }


}

